package com.cn.codebrush.链表;

/**
 * @Author Boolean
 * @Date 2022/6/14 21:41
 * @Version 1.0
 */
public class No92反转链表II {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        l1.next = node1;
        node1.next=node2;
        /*node2.next=node3;
        node3.next=node4;*/
        System.out.println(reverseBetween(l1,1,3));
    }


    public static   ListNode reverseBetween(ListNode head, int left, int right) {
        if(left == right){
            return head;
        }
        ListNode preNode = null;
        ListNode endNextNode = null;
        ListNode startNode = null;
        int count = 1;
        ListNode temp = head;

        while(temp != null){
            if(count == left-1){
                preNode = temp;
            }
            if(count == left){
                startNode = temp;
            }
            if(count == right){
                endNextNode = temp.next;
                temp.next = null;
            }
            temp = temp.next;
            count++;
        }

        ListNode newNode = endNextNode;
        while(startNode != null){
            ListNode restemp = startNode.next;
            startNode.next = newNode;
            newNode = startNode;
            startNode = restemp;
        }
        if(preNode != null){
            preNode.next = newNode;
        }else {
            head = newNode;
        }

        return head;
    }
}
